﻿using System;
using System.Threading.Tasks;
using Xiaowei.Helpers;
using Xiaowei.Settings;

namespace Xiaowei.Services
{
    public enum UpdateReminder
    {
        NoReminder,
        LatestAlready,
        OptionalUpdate,
        ForceUpdate
    }
    public static class VersionVerification
    {
        public delegate void VerificationHandler(UpdateReminder reminder);
        public static event VerificationHandler Finished;

        public static UpdateReminder Reminder { get; set; } = UpdateReminder.NoReminder;
        public static async Task VerifyAsync(bool auto = false)
        {
            var ack = await ServerApi.Instance.CheckVersion(AppState.Version.ToString()).ConfigureAwait(false);
            if (ack != null)
            {
                AppState.IsForceUpdate = ack.Force;
                Version verFromServer = Version.Parse(ack.Latest);
                if (AppState.Version < verFromServer)
                {
                    if (ack.Force)
                    {
                        RaiseFinishedEvent(UpdateReminder.ForceUpdate);
                    }
                    else
                    {
                        RaiseFinishedEvent(UpdateReminder.OptionalUpdate);
                    }
                }
                else
                {
                    if (auto)
                    {
                        RaiseFinishedEvent(UpdateReminder.NoReminder);
                    }
                    else
                    {
                        RaiseFinishedEvent(UpdateReminder.LatestAlready);
                    }
                }
            }
        }

        private static void RaiseFinishedEvent(UpdateReminder reminder)
        {
            Reminder = reminder;
            Finished?.Invoke(reminder);
        }

        private static bool inBackground = true;
        public static void RunInBackground()
        {
            if (!inBackground)
            {
                inBackground = true;
                /*
                Task.Run(async() =>
                {
                    while (true)
                    {
                        await VerifyAsync(true).ConfigureAwait(false);
                        Task.Delay(DebugConfig.CheckVersionCycle).Wait();
                    }
                });
                */
            }
        }
    }
}
